package com.pocketsweet.ui;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;

import com.avos.avoscloud.AVAnalytics;
import com.avos.avoscloud.AVInstallation;
import com.avos.avoscloud.PushService;
import com.easemob.EMCallBack;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.pocketsweet.MLCache;
import com.pocketsweet.MLOrderTimer;
import com.pocketsweet.R;
import com.pocketsweet.C;
import com.pocketsweet.MLApplication;
import com.pocketsweet.MLContext;
import com.pocketsweet.chat.ui.activity.BaseActivity;
import com.pocketsweet.chat.ui.activity.RandomCallActivity;
import com.pocketsweet.chatlib.controller.MolianContactManager;
import com.pocketsweet.model.MLTestOrder;
import com.pocketsweet.model.MLUser;
import com.pocketsweet.service.UpdateService;
import com.pocketsweet.service.UserService;
import com.pocketsweet.service.shareApp;
import com.pocketsweet.service.shareApp.shareCompleteListener;
import com.pocketsweet.ui.uilib.MyAlertDialog;
import com.pocketsweet.utils.GetUri;
import com.pocketsweet.utils.ToolKits;
import com.umeng.update.UpdateConfig;

@ContentView(R.layout.activity_more)
public class More extends BaseActivity implements OnClickListener {

    @ViewInject(R.id.relMessageBecome)
    private LinearLayout relMessageBecome;

    @ViewInject(R.id.relLoverNotice)
    private LinearLayout relLoverNotice;

    @ViewInject(R.id.relApplyRecommend)
    private LinearLayout relApplyRecommend;

    @ViewInject(R.id.relMessageSetting)
    private LinearLayout relMessageSetting;

    @ViewInject(R.id.relChangePhone)
    private LinearLayout relChangePhone;

    @ViewInject(R.id.relSendGift)
    private LinearLayout relSendGift;

    @ViewInject(R.id.relGiveHighOpinion)
    private LinearLayout relGiveHighOpinion;

    @ViewInject(R.id.relFeedback)
    private LinearLayout relFeedback;

    @ViewInject(R.id.rekBlackList)
    private LinearLayout rekBlackList;

    @ViewInject(R.id.relUpdated)
    private LinearLayout relUpdated;

    @ViewInject(R.id.relCache)
    private LinearLayout relCache;

    @ViewInject(R.id.relAbout)
    private LinearLayout relAbout;

    @ViewInject(R.id.relLogout)
    private LinearLayout relLogout;

    private UpdateService myUpdateService;
    private shareApp myShareApp;// 分享app

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ViewUtils.inject(this);
        initListener();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (UserService.getCurrentUser().getType() == C.USER_TYPE_NORMAL) {
            relMessageBecome.setVisibility(View.VISIBLE);
            relApplyRecommend.setVisibility(View.GONE);
            relChangePhone.setVisibility(View.GONE);
            relLoverNotice.setVisibility(View.GONE);
        } else if (UserService.getCurrentUser().getType() == C.USER_TYPE_LOVER) {
            relApplyRecommend.setVisibility(View.VISIBLE);
            relMessageBecome.setVisibility(View.GONE);
            relChangePhone.setVisibility(View.VISIBLE);
            relLoverNotice.setVisibility(View.VISIBLE);
        } else {
            relApplyRecommend.setVisibility(View.GONE);
            relMessageBecome.setVisibility(View.GONE);
            relLoverNotice.setVisibility(View.VISIBLE);
            relChangePhone.setVisibility(View.VISIBLE);
        }
    }

    private void initListener() {
        relApplyRecommend.setOnClickListener(this);
        relMessageBecome.setOnClickListener(this);
        relLoverNotice.setOnClickListener(this);
        relChangePhone.setOnClickListener(this);
        relMessageSetting.setOnClickListener(this);
        relSendGift.setOnClickListener(this);
        relGiveHighOpinion.setOnClickListener(this);
        relFeedback.setOnClickListener(this);
        rekBlackList.setOnClickListener(this);
        relUpdated.setOnClickListener(this);
        relCache.setOnClickListener(this);
        relAbout.setOnClickListener(this);
        relLogout.setOnClickListener(this);
    }

    public void back(View v) {
        More.this.finish();
    }

    private void setCompleteShare() {// 设置分享的任务完成情况
        if (MLContext.getTask(MLContext.TASK_INVITE_FRIEND) != C.TASK_FINISH) { // 如果分享未完成和任务未领取，则可领取任务
            MLContext.saveTask(MLContext.TASK_INVITE_FRIEND, C.TASK_GET_REWARD);
        }
    }

    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        switch (arg0.getId()) {
            case R.id.relApplyRecommend:
                Intent intenApplyRecommend = new Intent(More.this,
                        ApplyForRecommend.class);
                startActivity(intenApplyRecommend);
                break;
            case R.id.relMessageBecome:
                Intent intentBecome = new Intent(More.this, Identification.class);
                startActivity(intentBecome);
                break;
            case R.id.relLoverNotice:
                Intent intentLoverNotice = new Intent(More.this, WebViews.class);
                intentLoverNotice.putExtra("url",
                        "http://www.pocketsweet.com/howtobe");
                intentLoverNotice.putExtra("title", "口袋恋人须知");
                startActivity(intentLoverNotice);
                AVAnalytics.onEvent(this, "口袋恋人须知");
                break;
            case R.id.relChangePhone:

                Intent intentChangePhone = new Intent(More.this,
                        IdentificationMobileConfirm.class);
                startActivity(intentChangePhone);
                break;

            case R.id.relMessageSetting:
                Intent intentSetting = new Intent(More.this, MessageSetting.class);
                startActivity(intentSetting);
                break;
            case R.id.relSendGift:
                myShareApp = new shareApp(More.this);
                myShareApp.setCompleteListener(new shareCompleteListener() {

                    @Override
                    public void onComplate() {
                        setCompleteShare();
                    }
                });
                myShareApp.startShare();
                break;
            case R.id.relFeedback:
                Intent feedBackIntent = new Intent(More.this, FeedBack.class);
                startActivity(feedBackIntent);
                break;
            case R.id.relGiveHighOpinion:
                Intent i = GetUri.getIntent(More.this);
                boolean b = GetUri.judge(More.this, i);
                if (b == false) {
                    startActivity(i);
                } else {
                    ToolKits.toast(More.this, "无应用商店");
                }
                break;
            case R.id.relUpdated:
                myUpdateService = new UpdateService(More.this, false);
                UpdateConfig.setDebug(true);
                myUpdateService.update();
                break;
            case R.id.rekBlackList:
                Intent blackListIntent = new Intent(More.this, BlackList.class);
                startActivity(blackListIntent);
                AVAnalytics.onEvent(this, "黑名单管理页面访问");
                break;
            case R.id.relLogout:
                final MyAlertDialog dialog = new MyAlertDialog(More.this).builder()
                        .setMsg("是否退出账号？").setTitle("退出账号")
                        .setNegativeButton("取消", new OnClickListener() {
                            @Override
                            public void onClick(View v) {

                            }
                        });
                dialog.setPositiveButton("确定", new OnClickListener() {
                    @SuppressLint("SimpleDateFormat")
                    @Override
                    public void onClick(View v) {

                        cancleChannel();
                        // 退订之后需要重新保存 Installation
                        AVInstallation.getCurrentInstallation().saveInBackground();
                        final ProgressDialog pd = new ProgressDialog(More.this);
                        String st = getResources().getString(
                                R.string.Are_logged_out);
                        pd.setMessage(st);
                        pd.setCanceledOnTouchOutside(false);
                        pd.show();
                        MLApplication.getInstance().logout(new EMCallBack() {

                            @Override
                            public void onSuccess() {
                                More.this.runOnUiThread(new Runnable() {
                                    public void run() {
                                        // 重新显示登陆页面
                                        MLUser.logOut();
                                        MLContext.deleteAll(); // 删除所有sharepreference
                                        MLCache mlCache = new MLCache(More.this);
                                        mlCache.clearCache();
                                        MLOrderTimer.getInstance().clear();
                                        pd.dismiss();
                                        MLApplication.getInstance().setIsLogin(
                                                false);
                                        Intent intent2 = new Intent(More.this,
                                                TempMain.class);
                                        More.this.startActivity(intent2);
                                        More.this.finish();
                                        if(!Main.getInstance().isFinishing()) {
                                            Main.getInstance().finish();
                                        }
                                    }
                                });
                            }

                            @Override
                            public void onProgress(int progress, String status) {

                            }

                            @Override
                            public void onError(int code, String message) {

                            }
                        });
                    }
                });
                dialog.show();

                break;
            case R.id.relAbout:
                Intent aboutIntent = new Intent(More.this, About.class);
                startActivity(aboutIntent);
                break;
            case R.id.relCache:
                final MyAlertDialog dialogCache = new MyAlertDialog(More.this)
                        .builder().setMsg("是否清理图片缓存？").setTitle("清理缓存")
                        .setNegativeButton("取消", new OnClickListener() {
                            @Override
                            public void onClick(View v) {

                            }
                        });
                dialogCache.setPositiveButton("确定", new OnClickListener() {
                    @SuppressLint("SimpleDateFormat")
                    @Override
                    public void onClick(View v) {
                        MolianContactManager.getInstance().deleteCache();
                        ToolKits.toast(More.this, "已清除");
                    }
                });
                dialogCache.show();
                break;
        }

    }


    public boolean checkBrowser(String packageName) {
        if (packageName == null || "".equals(packageName))
            return false;
        try {
            ApplicationInfo info = getPackageManager().getApplicationInfo(
                    packageName, PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }

    private void cancleChannel() {
        PushService.unsubscribe(More.this, UserService.getCurrentUserId());
        if (UserService.getCurrentUser().getType() == C.USER_TYPE_LOVER
                || UserService.getCurrentUser().getType() == C.USER_TYPE_RECOMMENDED) {
            if (UserService.getCurrentUser().getGender() == C.USER_GENDER_MALE) {
                PushService.unsubscribe(More.this, "SweetMale");
            } else if (UserService.getCurrentUser().getGender() == C.USER_GENDER_FEMALE) {
                PushService.unsubscribe(More.this, "SweetFemale");
            }
        }

    }

}
